import { defineStore } from 'pinia'
import { useMediaStore } from '@/stores/modules/media'

import { useWoundedfzStore } from '@/stores/modules/woundedfz'
import { queryDict } from '@/utils/api/dict/dict'
import {
  woundedFind, //查询伤票及相关信息
  woundedDelete, //删除媒体数据
  woundedMediaAdd, //新增媒体数据
  woundedMediaFind, //查询媒体数据
  woundedAfter, //后送确认
  woundedEdit, //编辑伤票
  woundedScan, //扫描码新增伤票信息并查询
} from '@/utils/api/woundedfz/woundedfz'
export const useHandleWoundedStore = defineStore(
  'handleWounded',
  () => {
    const woundedfzStore = useWoundedfzStore()
    const mediaStore = useMediaStore()
    const TagCode = ref('') //伤票编号
    const TagUuid = ref('') //伤票UUID
    const TagStatus = ref(woundedfzStore.TagStatus) //伤票状态
    const TagStatusName = ref('') //伤票状态名称
    //后送去向字典数据
    const goDestList = <AnyArray>[]
    const goDestData: AnyObject = reactive({ goDestList })
    // 获取后送去向字典数据
    const getGodestList = async () => {
      const dictData = await queryDict({ DictType: 'GoDest', DictStatus: 'Normal' })
      goDestData.goDestList = dictData.data
    }
    //视频列表
    const videoList: any = reactive({
      list: [],
    })
    //图片列表
    const imageList: any = reactive({
      list: [],
    })
    //音频列表
    const audioList: any = reactive({
      list: [],
    })
    // 信息
    const woundedData: any = reactive({
      Name: '', //姓名
      SexName: '', //性别
      Department: '', //部门
      Age: '', //年龄
      tagFiles: {
        audio: [], //音频
        image: [], //图片
        video: [], //视频
      }, //伤情记录
      GoDest: '', //后送去向
      InjuryRemark: '', //伤情描述
    })
    //清空数据
    const clearData = () => {
      Object.assign(woundedData, {
        Name: '', //姓名
        SexName: '', //性别
        Department: '', //部门
        Age: '', //年龄
        tagFiles: {
          audio: [], //音频
          image: [], //图片
          video: [], //视频
        }, //伤情记录
        GoDest: '', //后送去向
        InjuryRemark: '', //伤情描述
      })
      videoList.list = []
      imageList.list = []
      audioList.list = []
    }
    //编辑伤票
    const editWounded = async (type: string) => {
      const { Name, Sex, Department, Age, InjuryRemark } = woundedData
      const { GoDest } = woundedData
      let data = {}
      if (type == 'TagStatus1') {
        data = { Name, Sex, Department, Age, InjuryRemark }
      } else {
        data = { Name, Sex, Department, Age, InjuryRemark, GoDest }
      }
      const res: any = await woundedEdit({
        TagUuid: TagUuid.value,
        ...data,
      })
      uni.showToast({
        title: '编辑成功',
        icon: 'success',
        duration: 2000,
        mask: true,
        success: async () => {
          setTimeout(async () => {
            uni.navigateBack()
          }, 2000)
        },
      })
    }
    //后送确认
    const afterWounded = async () => {
      console.log('打印后送信息', woundedData)

      if (!woundedData.GoDest) {
        uni.showToast({
          title: '请选择后送去向',
          icon: 'none',
          duration: 2000,
          mask: true,
        })
        return
      }
      await woundedAfter({
        TagCode: TagCode.value,
        GoDest: woundedData.GoDest,
      })
      uni.showToast({
        title: '后送确认成功',
        icon: 'success',
        duration: 2000,
        mask: true,
        success: async () => {
          setTimeout(async () => {
            uni.navigateBack()
          }, 500)
        },
      })
    }
    // 查询伤票及相关信息
    const findWounded = async (code: string) => {
      uni.showLoading({
        title: '加载数据中...',
        mask: true,
      })
      const res: any = await woundedFind({
        TagCode: code,
      })
      TagCode.value = res.data.TagCode
      TagUuid.value = res.data.TagUuid
      TagStatus.value = res.data.TagStatus
      TagStatusName.value = res.data.TagStatusName
      const {
        Name, //姓名
        Sex, //性别
        Department, //部门
        Age, //年龄
        tagFiles, //伤情记录
        GoDest, //后送去向
        InjuryRemark, //伤情描述
      } = res.data
      Object.assign(woundedData, {
        Name, //姓名
        Sex, //性别
        Department, //部门
        Age, //年龄
        tagFiles, //伤情记录
        GoDest, //后送去向
        InjuryRemark, //伤情描述
      })
      //视频列表
      videoList.list = handleMediaData(tagFiles.vedio, 'video') || []
      //图片列表
      imageList.list = handleMediaData(tagFiles.img, 'image') || []
      //音频列表
      audioList.list = handleMediaData(tagFiles.sound, 'audio') || []
      console.log('打印伤情信息', woundedData)
      uni.hideLoading()
      return res.data
    }
    //待分配扫码进入查询数据
    const scanWounded = async (code: string) => {
      uni.showLoading({
        title: '加载数据中...',
        mask: true,
      })
      const res: any = await woundedScan({
        TagCode: code,
      })

      TagCode.value = res.data.TagCode
      TagUuid.value = res.data.TagUuid
      TagStatus.value = res.data.TagStatus
      const {
        Name, //姓名
        Sex, //性别
        Department, //部门
        Age, //年龄
        tagFiles, //伤情记录
        GoDest, //后送去向
        InjuryRemark, //伤情描述
      } = res.data
      Object.assign(woundedData, {
        Name, //姓名
        Sex, //性别
        Department, //部门
        Age, //年龄
        tagFiles, //伤情记录
        GoDest, //后送去向
        InjuryRemark, //伤情描述
      })
      //视频列表
      videoList.list = handleMediaData(tagFiles?.vedio, 'video') || []
      //图片列表
      imageList.list = handleMediaData(tagFiles?.img, 'image') || []
      //音频列表
      audioList.list = handleMediaData(tagFiles?.sound, 'audio') || []
      console.log('打印伤情信息', woundedData)
      uni.hideLoading()
      return res.data
    }
    //处理媒体数据
    const handleMediaData = (arr: AnyArray, type: string) => {
      if (arr?.length > 0 && arr) {
        arr.map((item: any) => {
          item.src = mediaStore.baseURL + '/' + item.FileUrl
        })
        if (type == 'audio') {
          const innerAudioContext: any = uni.createInnerAudioContext()
          arr.map((item: any) => {
            item.src = mediaStore.baseURL + '/' + item.FileUrl
            innerAudioContext.src = item.src
            innerAudioContext.onCanplay(() => {
              item.max = parseInt(innerAudioContext.duration)
            })
            item.max = parseInt(innerAudioContext.duration)
            item.time = 0
            item.currentTime = 0
            item.isplay = false
          })
        }
        console.log('打印媒体数据', arr)
        return arr
      }
    }

    // 媒体数据 发送上传请求
    const upLoadFile = async (path: any, type: string) => {
      let mediaType = type
      uni.uploadFile({
        url: mediaStore.baseURL + '/api/file/fileUp',
        filePath: path,
        name: 'file',
        formData: {
          storagePath: type == 'image' ? 'img' : 'file',
        },
        success: async (res: any) => {
          if (res.statusCode === 200) {
            let data: any = JSON.parse(res.data)
            let src = data.data.files[0] || ''
            console.log('上传成功', data, mediaType, src)

            if (src) {
              switch (mediaType) {
                case 'image':
                  await addMedia(src, 'image')
                  break
                case 'video':
                  await addMedia(src, 'video')
                  break
                case 'audio':
                  await addMedia(src, 'audio')
                  break
              }
            } else {
              uni.showToast({
                title: '未知错误',
              })
            }
          } else {
            uni.hideLoading()
            uni.showToast({
              title: '上传失败',
              icon: 'error',
              duration: 2000,
              mask: true,
            })
          }
        },
        fail: (res: any) => {
          uni.showToast({
            title: '上传失败',
            icon: 'error',
            duration: 2000,
            mask: true,
          })
        },
      })
    }
    // 新增media数据
    const addMedia = async (src: string, type: string) => {
      const res: any = await woundedMediaAdd({
        FileUrl: src,
        UuidCode: TagUuid.value,
        FileType: 'FileType1',
        FileForm: type == 'image' ? 'FileForm2' : type == 'video' ? 'FileForm1' : 'FileForm3',
      })
      await findMedia(type)
    }
    // 查询media数据
    const findMedia = async (type: string) => {
      const res: any = await woundedMediaFind({
        FileType: 'FileType1',
        UuidCode: TagUuid.value,
        FileForm: type == 'image' ? 'FileForm2' : type == 'video' ? 'FileForm1' : 'FileForm3',
      })
      switch (type) {
        case 'image':
          imageList.list = handleMediaData(res.data, 'image') || []
          break
        case 'video':
          videoList.list = handleMediaData(res.data, 'video') || []
          break
        case 'audio':
          audioList.list = handleMediaData(res.data, 'audio') || []
          break
      }
      uni.hideLoading()
      uni.showToast({
        title: '上传成功',
        icon: 'success',
        duration: 2000,
        mask: true,
      })
    }
    //上传视频
    const uploadVideo = async (type: string) => {
      uni.chooseVideo({
        maxDuration: 60,
        sourceType: [type],
        success: async (res: any) => {
          uni.showLoading({
            title: '上传中',
            mask: true,
          })
          console.log('上传视频路径', res.tempFilePath)
          await upLoadFile(res.tempFilePath, 'video')
        },
        fail: (res: any) => {
          uni.showToast({
            title: '关闭选择',
            icon: 'none',
            duration: 2000,
            mask: true,
          })
        },
      })
    }
    //上传图片
    const uploadImage = async (type: string) => {
      uni.chooseImage({
        count: 1, //默认9
        sourceType: [type],
        success: async (res: any) => {
          uni.showLoading({
            title: '上传中',
            mask: true,
          })
          console.log('上传图片路径', res.tempFilePaths[0])
          await upLoadFile(res.tempFilePaths[0], 'image')
        },
        fail: (res: any) => {
          uni.showToast({
            title: '关闭选择',
            icon: 'none',
            duration: 2000,
            mask: true,
          })
        },
      })
    }
    //上传音频
    const uploadAudio = async (type: string) => {
      let mediaType = type
      let fileList: any = ''
      // #ifdef H5
      uni.chooseFile({
        count: 1, //默认100
        type: 'all',
        success: async (res: any) => {
          uni.showLoading({
            title: '上传中',
            mask: true,
          })
          console.log('上传音频路径', res.tempFilePaths[0])
          await upLoadFile(res.tempFilePaths[0], mediaType)
        },
      })
      // #endif

      // #ifdef APP
      let main: any = plus.android.runtimeMainActivity()
      let Intent: any = plus.android.importClass('android.content.Intent')
      let intent = new Intent(Intent.ACTION_GET_CONTENT)
      intent.setType('*/*')
      intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true) //关键！多选参数
      intent.addCategory(Intent.CATEGORY_OPENABLE)
      main.startActivityForResult(intent, 200)
      // 获取回调
      main.onActivityResult = function (requestCode: any, resultCode: any, data: any) {
        let Activity: any = plus.android.importClass('android.app.Activity')
        let ContentUris: any = plus.android.importClass('android.content.ContentUris')
        let Cursor = plus.android.importClass('android.database.Cursor')
        let Uri: any = plus.android.importClass('android.net.Uri')
        let Build: any = plus.android.importClass('android.os.Build')
        let Environment: any = plus.android.importClass('android.os.Environment')
        let DocumentsContract: any = plus.android.importClass('android.provider.DocumentsContract')

        // 给系统导入 contentResolver
        let contentResolver = main.getContentResolver()
        plus.android.importClass(contentResolver)
        // 返回路径
        let path = ''
        if (resultCode == Activity.RESULT_OK) {
          if (data.getData() != null) {
            let uri = data.getData()
            //this 当前mainClass实例
            path = getPath(this, uri)
            if (path) {
              console.log('path-->', data, path)
              uni.showLoading({
                title: '正在上传文件...',
              })
              upLoadFile('file://' + path, 'audio')
            } else {
              uni.showToast({
                title: '文件获取失败',
              })
            }
          } else {
            try {
              let ClipData: any = plus.android.importClass('android.content.ClipData')
              let clipData = new ClipData()
              clipData = data.getClipData()
              if (clipData != null) {
                for (let i = 0; i < clipData.getItemCount(); i++) {
                  let item = clipData.getItemAt(i)
                  let uri = item.getUri()
                  let url = getPath(this, uri)
                  fileList.push(url)
                }
              }
              console.log('fileList--->', fileList)
            } catch (e) {
              console.log(e)
            }
          }
          // console.log(path);
        } else {
          // console.log(path);
        }

        function getPath(context: any, uri: any) {
          try {
            let isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT
            if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
              // ExternalStorageProvider
              //一些三方的文件浏览器会进入到这个方法中，例如ES
              //QQ文件管理器不在此列
              if (isExternalStorageDocument(uri)) {
                let docId = DocumentsContract.getDocumentId(uri)
                let split = docId.split(':')
                let type = split[0]
                // 如果是手机内部存储
                if ('primary' == type.toLowerCase()) {
                  return Environment.getExternalStorageDirectory() + '/' + split[1]
                } else {
                  return '/storage/' + type + '/' + split[1]
                }
              }
              // DownloadsProvider
              else if (isDownloadsDocument(uri)) {
                let id = DocumentsContract.getDocumentId(uri)
                if (id.indexOf('raw:') > -1) {
                  id = id.replace('raw:', '')
                }
                // 不同系统获取的id开头可能不一样，在这后面便是真实的地址
                if (id.substring(0, 5) == 'msf:') {
                  return id.substring(5, id.length)
                }
                let contentUri = ContentUris.withAppendedId(
                  Uri.parse('content://downloads/public_downloads'),
                  ContentUris.parseId(uri),
                )
                return getDataColumn(context, contentUri, null, null)
              }
              // MediaProvider
              else if (isMediaDocument(uri)) {
                let MediaStore: any = plus.android.importClass('android.provider.MediaStore')
                let docId = DocumentsContract.getDocumentId(uri)
                let split = docId.split(':')
                let type = split[0]
                let contentUri = null

                if ('image' == type.toLowerCase()) {
                  contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
                } else if ('video' == type.toLowerCase()) {
                  contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI
                } else if ('audio' == type.toLowerCase()) {
                  contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
                }
                let selection = '_id=?'
                let selectionArgs = [split[1]]
                return getDataColumn(context, contentUri, selection, selectionArgs)
              }
            }
            // MediaStore (and general)
            else if ('content' == uri.getScheme().toLowerCase()) {
              if (isGooglePhotosUri(uri)) {
                return uri.getLastPathSegment()
              } else if (isQQMediaDocument(uri)) {
                let paths = uri.getPath()
                let Environment: any = plus.android.importClass('android.os.Environment')
                let fileDir = Environment.getExternalStorageDirectory()
                let files: any = plus.android.importClass('java.io.File')
                let file = new files(fileDir, paths.substring('/QQBrowser'.length, paths.length))
                return file.getPath()
              }

              return getDataColumn(context, uri, null, null)
            }
            // File
            else if ('file' == uri.getScheme().toLowerCase()) {
              return uri.getPath()
            }
            return null
          } catch (e) {
            console.log(e)
            return null
          }
        }

        // 通过uri 查找出绝对路径
        function getDataColumn(context: any, uri: any, selection: any, selectionArgs: any) {
          try {
            let MediaStore: any = plus.android.importClass('android.provider.MediaStore')
            let cursor = null
            let column = MediaStore.MediaColumns.DATA
            let projection = [column]
            cursor = context
              .getContentResolver()
              .query(uri, projection, selection, selectionArgs, null)
            if (cursor != null && cursor.moveToFirst()) {
              let column_index = cursor.getColumnIndexOrThrow(column)
              return cursor.getString(column_index)
            }
          } catch (e) {
            console.log(e)
            return null
          }
        }

        function isExternalStorageDocument(uri: any) {
          return 'com.android.externalstorage.documents' == uri.getAuthority() ? true : false
        }

        function isDownloadsDocument(uri: any) {
          return 'com.android.providers.downloads.documents' == uri.getAuthority() ? true : false
        }

        function isMediaDocument(uri: any) {
          return 'com.android.providers.media.documents' == uri.getAuthority() ? true : false
        }
        /**
         * 使用第三方qq文件管理器打开
         *
         * @param uri
         * @return
         */
        function isQQMediaDocument(uri: any) {
          return 'com.tencent.mtt.fileprovider' == uri.getAuthority() ? true : false
        }
        /**
         * @param uri The Uri to check.
         * @return Whether the Uri authority is Google Photos.
         */
        function isGooglePhotosUri(uri: any) {
          return 'com.google.android.apps.photos.content' == uri.getAuthority() ? true : false
        }
      }
      // #endif
    }
    //删除媒体数据
    const deleteMediaData = async (FileUuid: string) => {
      return new Promise((resolve, reject) => {
        uni.showModal({
          title: '提示',
          content: '确定要删除吗？',
          confirmText: '确定',
          cancelText: '取消',
          confirmColor: '#02bdc6',
          success: async (res: any) => {
            if (res.confirm) {
              const res: any = await woundedDelete([FileUuid])
              if (res.code == 0) {
                uni.showToast({
                  title: '删除成功',
                  icon: 'success',
                  duration: 2000,
                  mask: true,
                })
                resolve(res)
              } else {
                uni.showToast({
                  title: res.msg,
                  icon: 'error',
                  duration: 2000,
                  mask: true,
                })
                reject(res)
              }
            }
          },
        })
      })
    }
    const deleteMedia = async (item: any, index: number, type: string) => {
      console.log('删除媒体数据', item, type)
      switch (type) {
        case 'video':
          await deleteMediaData(item.FileUuid)
          videoList.list.splice(index, 1)
          break
        case 'image':
          await deleteMediaData(item.FileUuid)
          imageList.list.splice(index, 1)
          break
        case 'audio':
          await deleteMediaData(item.FileUuid)
          audioList.list.splice(index, 1)
          break
      }
    }
    return {
      TagCode, //标签编号
      TagUuid, //标签UUID
      TagStatus, //标签状态
      findWounded, //查询伤票相关信息
      woundedData, //伤情信息
      uploadVideo, //上传视频
      uploadAudio, //上传音频
      uploadImage, //上传图片
      getGodestList, //获取后送去向字典数据
      upLoadFile, //上传文件
      goDestData, //后送去向字典数据
      videoList, //视频列表
      imageList, //图片列表
      audioList, //音频列表
      deleteMedia, //删除媒体数据
      editWounded, //编辑伤情信息
      afterWounded, //后送确认
      scanWounded, //扫码伤情信息
      clearData, //清空数据
    }
  },
  {
    // 配置持久化
    persist: {
      // 调整为兼容多端的API
      storage: {
        setItem(key, value) {
          uni.setStorageSync(key, value)
        },
        getItem(key) {
          return uni.getStorageSync(key)
        },
      },
      paths: ['goDestData'],
    },
  },
)
